package com.example.recite_words.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.recite_words.MainActivity;
import com.example.recite_words.R;
import com.example.recite_words.util.MyDatabaseHelper;
import com.example.recite_words.util.MyListViewCursorAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.File;
import java.io.IOException;

public class Main extends MainActivity {
    private Button battle,sameTime,sameProb;
    private ImageView mine;
    private LinearLayout buttons;
    private PopupWindow pop;
    private Spinner spinner;
    private ImageView book;
    private TextView rank,win_rate,mTextView;
    private EditText mEditText;
    private ListView mListView;
    private ImageView mImageView;
    private ImageView wrongBook;
    Cursor cursor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ContextCompat.checkSelfPermission(Main.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                !=
                PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(Main.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        else {
            if (new_start == 0) {
                try {
                    MainActivity.TheUser = MainActivity.TheUser.ReadUser(Main.this);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                if (MainActivity.TheUser.getCookie() <= 0) {
                    Intent login_intent = new Intent(Main.this, Login.class);
                    startActivity(login_intent);
                }
                new_start = 1;
            }
        }
        setContentView(R.layout.activity_main);
        battle=findViewById(R.id.battle);
       // popview=getLayoutInflater().inflate(R.layout.pop_item,null);
        buttons=findViewById(R.id.buttons);
        mine=findViewById(R.id.mine);
        Uri uri = MainActivity.TheUser.IconToUri();
        if(uri != null){
            mine.setImageURI(uri);
        }
        else {
            mine.setImageResource(R.drawable.user_icon);
        }
//        sameTime=findViewById(R.id.sameTime);
//        sameProb=findViewById(R.id.sameProb);
        spinner=(Spinner) findViewById(R.id.spinner);
        book=findViewById(R.id.book);
        rank=findViewById(R.id.rank);
        win_rate=findViewById(R.id.win_rate);
        mTextView = (TextView) findViewById(R.id.textview);
        mEditText = (EditText) findViewById(R.id.edittext);
        mListView = (ListView) findViewById(R.id.listview);
        mImageView = (ImageView) findViewById(R.id.imageview);

        wrongBook=(ImageView)findViewById(R.id.main_wrong);
        wrongBook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, Wrongbook.class));
            }
        });

        battle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                pop=new PopupWindow(popview,600,500,true);
//                pop.setOutsideTouchable(true);
//                pop.setFocusable(true);
//                pop.showAtLocation(rvlayout, Gravity.CENTER,0,500);
//                if(buttons.getVisibility()==View.INVISIBLE) buttons.setVisibility(View.VISIBLE);
//                else if(buttons.getVisibility()==View.VISIBLE) buttons.setVisibility(View.INVISIBLE);
                startActivity(new Intent(Main.this, Waiting.class));
            }
        });
        mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, Setting.class));
            }
        });

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            //当item被选择后调用此方法
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //获取我们所选中的内容
                String s = parent.getItemAtPosition(position).toString();
                if (s.equals("四级词书")){
                    book.setImageResource(R.drawable.book1);
                    //win_rate.setText("1");
                }else if(s.equals("六级词书")){
                    book.setImageResource(R.drawable.cet6);
                }else if(s.equals("托福词书")){
                    book.setImageResource(R.drawable.toefl);
                }

                //弹一个吐司提示我们所选中的内容
               // Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
            }
            //只有当patent中的资源没有时，调用此方法
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
//
//        sameTime.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(Main.this, Waiting.class));
//            }
//        });
//
//        sameProb.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(Main.this, Waiting.class));
//            }
//        });

        //设置删除图片的点击事件
        mImageView.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          public void onClick(View v) {
                                              //把EditText内容设置为空
                                              mEditText.setText("");
                                              //把ListView隐藏
                                              mListView.setVisibility(View.GONE);
                                          }
                                      });
            //EditText添加监听
            mEditText.addTextChangedListener(new TextWatcher() {

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}//文本改变之前执行

                @Override
                //文本改变的时候执行
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //如果长度为0
                    if (s.length() == 0) {
                        //隐藏“删除”图片
                        mImageView.setVisibility(View.GONE);
                    } else {//长度不为0
                        //显示“删除图片”
                        mImageView.setVisibility(View.VISIBLE);
                        //显示ListView
                        showListView();
                    }
                }
                public void afterTextChanged(Editable s) { }//文本改变之后执行
            });

            mTextView.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    //如果输入框内容为空，提示请输入搜索内容
                    if(TextUtils.isEmpty(mEditText.getText().toString().trim())){
                        //ToastUtils.showToast(context,"请输入您要搜索的内容");
                        Toast.makeText(Main.this, "请输入您要搜索的内容", Toast.LENGTH_SHORT).show();
                    }else {
                        //判断cursor是否为空
                        if (cursor != null) {
                            int columnCount = cursor.getCount();
                            if (columnCount == 0) {
                                Toast.makeText(Main.this, "请输入您要搜索的内容", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                }
            });




//        Button time = findViewById(R.id.main_time);
//        Button num = findViewById(R.id.main_num);
//        num.setOnClickListener(new View.OnClickListener(){
//
//            @Override
//            public void onClick(View v) {
//                Intent match_intent = new Intent();
//                match_intent.setClass(Main.this, Match.class);
//                startActivity(match_intent);
//            }
//        });
    }
    private void showListView() {
        mListView.setVisibility(View.VISIBLE);
        //获得输入的内容
        String str = mEditText.getText().toString().trim();
        //获取数据库对象
       // MyOpenHelper myOpenHelper = new MyOpenHelper(getApplicationContext());
        MyDatabaseHelper db=new MyDatabaseHelper(this);
        try {
            db.createDB();
        } catch (IOException ioe) {
            throw new Error("Database not created....");
        }

        try {
            db.openDB();
        } catch (SQLException sqle) {
            throw sqle;
        }
        SQLiteDatabase db1;
        db1= openOrCreateDatabase("words", Context.MODE_PRIVATE, null);
//        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
//        //得到cursor
        cursor = db1.rawQuery("select id as _id,words,translation from sheet1 where words like '%" + str + "%'", null);
        //Cursor cursor = db1.rawQuery("select * from sheet1 where words like spite", null);
        MyListViewCursorAdapter adapter = new MyListViewCursorAdapter(this, cursor);
//
        mListView.setAdapter(adapter);
//
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //把cursor移动到指定行
                cursor.moveToPosition(position);
                String meaning = cursor.getString(cursor.getColumnIndexOrThrow("translation"));
                Toast.makeText(Main.this, meaning, Toast.LENGTH_SHORT).show();
            }
        });
    }


}
